package ee.siimoliver.chat.server;

import java.util.LinkedList;

public class InputBuffer {

	private LinkedList<HttpMessage> inputBuffer;
	private boolean isWritable = false;
	
	private InputBuffer() {
		inputBuffer = new LinkedList<HttpMessage>();
	}
	
	private static class SingletonHolder { 
        public static final InputBuffer instance = new InputBuffer();
	}

    public static InputBuffer getInstance() {
            return SingletonHolder.instance;
    }
	
	/**
	 * Adds message to the outbound queue.
	 * Also logs message.
	 * @param msg Message to send
	 */
	public synchronized void addMessage(byte[] msg) {
		if (isWritable) {
			setNotWritable();
			inputBuffer.add(new HttpMessage(msg));
			System.out.println(new String(msg));
			this.notifyAll();
		}
	}
	
	/**
	 * Adds message to the outbound queue.
	 * Also logs message.
	 * @param msg Message to send
	 */
	public synchronized void addMessage(HttpMessage msg) {
		if (isWritable) {
			setNotWritable();
			inputBuffer.add(msg);
			System.out.println(msg.toString());
			this.notifyAll();
		}
	}
	
	/**
	 * Gets message from outbound queue.
	 * @return Message
	 */
	public synchronized HttpMessage getMessage() { 
		try {
			while (inputBuffer.isEmpty())
				this.wait(); 
		} catch (InterruptedException e) {}
		return inputBuffer.removeFirst();
	}
	
	public synchronized void clearBuffer() {
		inputBuffer.clear();
	}
	
	public synchronized boolean isInputBufferEmpty() {
		return inputBuffer.isEmpty();
	}
	
	public synchronized void setWritable() {
		clearBuffer();
		isWritable = true;
	}
	
	public synchronized void setNotWritable() {
		isWritable = false;
	}
}
